package com.bit.inmap;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMS_Act extends Service {

	private String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

	private String gpsaa;
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		private double mLat;
		private double mLon;
		private String PhonNum;

		public void onReceive(Context context, Intent intent) {

			LocationManager lmh = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

			Location lastKnownLocation = null;

			lastKnownLocation = lmh
					.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

			mLat = lastKnownLocation.getLatitude();
			mLon = lastKnownLocation.getLongitude();

			String gps = String.valueOf(mLat);
			String gpsa = String.valueOf(mLon);

			String address = getAddressFromLocation(lastKnownLocation, Locale.KOREA);
			
			gpsaa = gps + gpsa;

			String ee="";
			String message = "";
			String Compare = "어디야";
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				Object[] pdus = (Object[]) bundle.get("pdus");

				for (Object pdu : pdus) {
					SmsMessage smsMessage = SmsMessage
							.createFromPdu((byte[]) pdu);
					message += smsMessage.getMessageBody();
					PhonNum = smsMessage.getDisplayOriginatingAddress();
					
					ee = smsMessage.getMessageBody();
				}
				
				
			}
			if (message.equals(Compare)) {
				smsManager(PhonNum, address);
			}
			intent = new Intent(context, GPSActivity.class);
			intent.putExtra("location", ee);
			GPSActivity.check = true;
			startActivity(intent);
			
			
		}
	};
	
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if (mReceiver != null)
			;
		{
			unregisterReceiver(mReceiver);
		}
		Toast.makeText(this, "서비스 종료", Toast.LENGTH_SHORT).show();
	}

	public int onStartCommand(Intent intent, int flags, int startId) {
		Toast.makeText(this, "서비스가시작되었습니다.", Toast.LENGTH_SHORT).show();
		IntentFilter filter = new IntentFilter(ACTION_SMS_RECEIVED);
		registerReceiver(mReceiver, filter);
		return SMS_Act.START_NOT_STICKY;

	}

	public IBinder onBind(Intent intent) {
		return null;
	}

	public void smsManager(String PhonNum, String latitude) {

		SmsManager smsManager = android.telephony.SmsManager.getDefault();

		smsManager.sendTextMessage(PhonNum, null, latitude, null, null);

	}

	public String getGps() {

		return gpsaa;
	}
    String getAddressFromLocation(Location location, Locale locale) {
        List<Address> addressList = null;
        Geocoder geocoder = new Geocoder(this, locale);
        
        //------------------------------------------------------------------
        // 지오코더를 이용하여 주소 리스트를 구합니다.
        
        try {
            addressList = geocoder.getFromLocation(
                location.getLatitude(),
                location.getLongitude(),
                1
            );
        } catch (IOException e) {
            Toast.makeText(this, "위치로부터 주소를 인식할 수 없습니다. 네트워크가 연결되어 있는지 확인해 주세요.", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            return "주소 인식 불가";
        }
        
        //------------------------------------------------------------------
        // 주소 리스트가 비어있는지 확인합니다. 비어 있으면, 주소 대신 그것이 없음을 알리는 문자열을 리턴합니다.
        
        if (1 > addressList.size()) {
            return "해당 위치에 주소 없음";
        }
        
        //------------------------------------------------------------------
        // 주소를 담는 문자열을 생성하고 리턴합니다.
        
        Address address = addressList.get(0);
        StringBuilder addressStringBuilder = new StringBuilder();
        for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
            addressStringBuilder.append(address.getAddressLine(i));
            if (i < address.getMaxAddressLineIndex())
                addressStringBuilder.append("\n");
        }

        return addressStringBuilder.toString();
    }

}
